package de.rj.urwalking.ui.fragments.dialog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockDialogFragment;

import de.rj.urwalking.R;

/**
 * 
 * @author rjj
 * 
 */
public class RegistrationDialogFragment extends SherlockDialogFragment implements OnClickListener {

	private EditText editEmail;
	private EditText editPassword;
	private Button okButton;
	private Button cancelButton;
	private EditText editPasswordRepeat;

	private boolean mPasswordsMatch;
	private boolean mEmailIsValid;
	private CheckBox termsOfUseCheckBox;

	public interface RegistrationDialogListener {
		void onFinishRegistrationDialog(String email, String password);
	}

	public RegistrationDialogFragment() {
		// Empty constructor required for DialogFragment
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_registration_dialog, container);
		
		// adjust dialog window size
		WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
		wmlp.gravity = Gravity.LEFT;

		// get references to UI elements
		editEmail = (EditText) view.findViewById(R.id.editEmail);
		editPassword = (EditText) view.findViewById(R.id.editPassword);
		editPasswordRepeat = (EditText) view.findViewById(R.id.editPasswordRepeat);
		termsOfUseCheckBox = (CheckBox) view.findViewById(R.id.termsOfUseCheckBox);
		okButton = (Button) view.findViewById(R.id.okButton);
		cancelButton = (Button) view.findViewById(R.id.cancelButton);

		// ok button is disabled at startup
		okButton.setEnabled(false);
		okButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);

		// setup listener for checkbox
		termsOfUseCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					tryEnablingOkButton();
				} else {
					okButton.setEnabled(false);
				}
			}
		});

		// setup listener for email field which checks its validity
		editEmail.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				if (checkEmailAddress(s.toString())) {
					mEmailIsValid = true;
					tryEnablingOkButton();
				} else {
					mEmailIsValid = false;
					okButton.setEnabled(false);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		PasswordTextWatcher passwordTextWatcher = new PasswordTextWatcher();
		editPassword.addTextChangedListener(passwordTextWatcher);
		editPasswordRepeat.addTextChangedListener(passwordTextWatcher);

		getDialog().setTitle(getString(R.string.register_verbose));

		// Show soft keyboard automatically
		editEmail.requestFocus();
		getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);

		return view;

	}

	/**
	 * Enables the ok button if certain conditions are met.
	 */
	protected void tryEnablingOkButton() {

		if (mEmailIsValid && mPasswordsMatch && termsOfUseCheckBox.isChecked()) {
			okButton.setEnabled(true);
		}
	}

	/**
	 * Checks the validity of the entered email address using a simple regular expression. 
	 * @param email
	 * @return
	 */
	protected boolean checkEmailAddress(String email) {

		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		boolean matchFound = m.matches();

		return matchFound;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.okButton:
			// Return credentials to activity
			RegistrationDialogListener activity = (RegistrationDialogListener) getActivity();
			activity.onFinishRegistrationDialog(editEmail.getText().toString(), editPassword.getText().toString());
			this.dismiss();
			break;
		case R.id.cancelButton:
			this.dismiss();
			break;
		default:
			break;
		}

	}

	/**
	 * Watches the password fields and checks if the contents match. If they don't, a warning is shown.
	 */
	private class PasswordTextWatcher implements TextWatcher {

		@Override
		public void afterTextChanged(Editable s) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (editPassword.getText().toString().equals(editPasswordRepeat.getText().toString())) {

				editPasswordRepeat.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
				editPassword.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

				mPasswordsMatch = true;
				tryEnablingOkButton();
			} else {
				mPasswordsMatch = false;
				okButton.setEnabled(false);

				editPasswordRepeat.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.indicator_input_error, 0);
				editPassword.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.indicator_input_error, 0);
			}
		}

	}

}
